<?php

namespace App\Http\Requests;

use App\Tool\Helper;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class DoctorAuth extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'department_id' => 'required',
            'name' => 'required',
            'skilled' => 'required',
            'phone' => [
                'required', function($attribute, $value, $fail) {
                    if (!Helper::hasPhone($value)) {
                        $fail('请输入正确的手机号码');
                        return;
                    }
                }
            ],
            'id_num' => [
                'required', function($attribute, $value, $fail) {
                    if (!Helper::is_idcard($value)) {
                        $fail('请输入正确的身份证号码');
                        return;
                    }
                }
            ],
            'cert_img' => 'required',
        ];
    }

    public function messages()
    {
        return [
            'department_id.required' => '请选择科室',
            'name.required' => '请输入姓名',
            'skilled.required' => '请输入个人简介',
            'phone.required' => '请输入手机号码',
            'id_num.required' => '请输入身份证号码',
            'cert_img.required' => '请上传证书',
        ];
    }

    protected function failedValidation(Validator $validator)
    {
        throw new HttpResponseException(response()->json([
            "code"  => 500,
            "msg"   => $validator->getMessageBag()->first(),
            "data"  => null,
        ], 200, [
            'Content-Type'=>'application/json; charset=UTF-8'
        ]));
    }
}
